package com.wzt.lianfirecontrol.http;

import android.app.Activity;
import android.content.Context;

import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.utils.StringUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpConnection {

    public synchronized static String getRequestWithOkHttp(Activity activity, String url){
        if (StringUtils.isEmpty(url)){
            return null;
        }
        try {
            OkHttpClient client = new OkHttpClient();
            Request request;
            if (UserInfoModel.isLogin(activity)) {
                request = new Request.Builder()
                        .url(url)
                        .addHeader("kdla-access-token", UserInfoModel.getUserToken(activity))
                        .build();
            }else {
                request = new Request.Builder()
                        .url(url)
                        .build();
            }


            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            return responseData;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public synchronized static String postRequestWithOkHttp(Activity activity, String url, HashMap<String, String> params){
        if (StringUtils.isEmpty(url)){
            return null;
        }
        try {
            OkHttpClient client = new OkHttpClient();
            Request request;
            if (UserInfoModel.isLogin(activity)) {
                request = new Request.Builder()
                        .url(url)
                        .addHeader("kdla-access-token", UserInfoModel.getUserToken(activity))
                        .post(Url.getPostRequestBody(params))
                        .build();
            } else {
                request = new Request.Builder()
                        .url(url)
                        .post(Url.getPostRequestBody(params))
                        .build();
            }

            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            return responseData;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 传递对象
     * @param context
     * @param url
     * @param url_params
     * @return
     */
    public synchronized static String postRequestByJsonWithOkHttp(Context context, String url, HashMap<String, String> url_params){
        if (StringUtils.isEmpty(url) || null == url_params){
            return null;
        }
        try {
            //1 . 拿到OkHttpClient对象
            OkHttpClient client = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true)
                    .connectTimeout(5, TimeUnit.SECONDS) //连接超时
                    .readTimeout(8, TimeUnit.SECONDS) //读取超时
                    .writeTimeout(8, TimeUnit.SECONDS) //写超时
                    .build();

            //添加一个json格式数据
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
            RequestBody requestBody = RequestBody.create(JSON, url_params.get("jsonObject"));
            //3 . 构建Request,将FormBody作为Post方法的参数传入
            Request request;
            if (UserInfoModel.isLogin(context)) {
                request = new Request.Builder()
                        .url(url)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("kdla-access-token", UserInfoModel.getUserToken(context))
                        .post(requestBody)
                        .build();
            } else {
                request = new Request.Builder()
                        .url(url)
                        .addHeader("Content-Type", "application/json")
                        .post(requestBody)
                        .build();
            }
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            return responseData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 传递对象
     * @param activity
     * @param url
     * @param file
     * @return
     */
    public synchronized static String postRequestByFileWithOkHttp(Activity activity, String url, File file){
        if (null == file){
            return null;
        }
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
            //添加一个json格式数据
            //MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            //RequestBody requestBody = RequestBody.create(JSON, file);//把文件与类型放入请求体

            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), requestBody)
                    .build();

            Request request = new Request.Builder()
                    //.addHeader("Content-Type", "application/json")
                    .url(url)
                    .post(multipartBody)
                    .build();

            //1 . 拿到OkHttpClient对象
            OkHttpClient client = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true)
                    .connectTimeout(3, TimeUnit.SECONDS) //连接超时
                    .readTimeout(8, TimeUnit.SECONDS) //读取超时
                    .writeTimeout(8, TimeUnit.SECONDS) //写超时
                    .build();
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            return responseData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String postRequestWithUrlConnection(final String url, final HashMap<String, String> params){
        if (StringUtils.isEmpty(url)){
            return null;
        }
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            String param = Url.getPostParamsStr(params);
            out.writeBytes(param);
            out.flush(); // 发送，清空缓存
            out.close(); // 关闭
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            // 设置此 httpUrlConnection 实例是否应该自动执行 http 重定向
            connection.setInstanceFollowRedirects(true);
            // 设定传值的内容类型是可序列化的java对象
            // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "UTF-8");
            InputStream in = connection.getInputStream();
            // 对获取的输入法进行读取
            reader = new BufferedReader(new InputStreamReader(in));
            String response = "";
            String line;
            while(null != (line = reader.readLine())){
                response += line;
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            if (null != reader){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != connection){
                connection.disconnect();
            }
        }
    }

}
